package com.joven.shelltest.utils.pdf;

        import com.itextpdf.awt.geom.Rectangle2D;
        import com.itextpdf.text.Image;
        import com.itextpdf.text.pdf.PdfContentByte;
        import com.itextpdf.text.pdf.PdfReader;
        import com.itextpdf.text.pdf.PdfStamper;
        import com.itextpdf.text.pdf.parser.ImageRenderInfo;
        import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
        import com.itextpdf.text.pdf.parser.RenderListener;
        import com.itextpdf.text.pdf.parser.TextRenderInfo;

        import java.nio.file.Files;
        import java.nio.file.Paths;
        import java.util.Optional;

/**
 * @Author wzj
 * @Date 2024-01-09 15:30
 **/
public class PdfSignUtil {

    public static void addSignSeal(String sourceFilePath, String targetFilePath, String imagePath) throws Exception {
        Image image = Image.getInstance(imagePath);
        image.scaleToFit(100, 100);
        PdfReader pdfReader = new PdfReader(sourceFilePath);
        int pageNumber = pdfReader.getNumberOfPages();
        PdfReaderContentParser parser = new PdfReaderContentParser(pdfReader);
        parser.processContent(pageNumber, new RenderListener() {
            @Override
            public void beginTextBlock() {

            }

            @Override
            public void renderText(TextRenderInfo textRenderInfo) {
                String text = textRenderInfo.getText();
                if (text != null && text.contains("joven")) {
                    Rectangle2D.Float textFloat = textRenderInfo.getBaseline().getBoundingRectange();
                    float x = textFloat.x;
                    float y = textFloat.y;
                    image.setAbsolutePosition(x + 28f, y - 60f);
                }
            }

            @Override
            public void endTextBlock() {

            }

            @Override
            public void renderImage(ImageRenderInfo imageRenderInfo) {

            }
        });
        PdfStamper stamper = new PdfStamper(pdfReader, Files.newOutputStream(Paths.get(targetFilePath)));
        PdfContentByte cvas = stamper.getUnderContent(pageNumber);
        //白底的印章图片  stamper.getUnderContent(pageNumber); 效果看起来是字在章上面。
        //透明的图片就需要用  getOverContent(pageNumber); 效果看起来是章在字上面。
        cvas.addImage(image);
        stamper.close();
        Optional.of(pdfReader).ifPresent(PdfReader::close);
    }

    public static void main(String[] args) throws Exception {
        addSignSeal("D:\\image\\test15.pdf","D:\\image\\test16.pdf","D:\\image\\sign.png");
    }
}
